package servlets.ads;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.JsonManager;

import org.jsoup.Jsoup;

import structures.User;

public class EndPayPalPayment extends HttpServlet {

	private static final long serialVersionUID = 5584254570392076805L;
	private static final String SETBOUGHTURLBASE = "http://localhost:8080/DatabaseRESTWebService/SetADBought?";
	private static final String NOTIFY = "http://localhost:8080/RESTEmailService/notify";
	private static final String GETUSERURLBASE = "http://localhost:8080/DatabaseRESTWebService/GetIdUserServlet?";
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response){
		BufferedReader reader;
		StringBuffer responseBuffer;
		URL url;
		JsonManager jsonManager;
		User user = null;
		jsonManager = new JsonManager();
		String idUser, success, idAdvertisement, returnUrl, inputLine, answer;
		idUser = request.getParameter("idUser");
		success = request.getParameter("success");
		idAdvertisement = request.getParameter("idAdvertisement");
		String emailOwner = request.getParameter("emailOwner");
		returnUrl = request.getParameter("returnUrl");
		
		if(success.equals("true")){
			
			try{
				url = new URL(GETUSERURLBASE + "idUser=" + idUser);
				answer = Jsoup.connect(url.toString()).ignoreContentType(true).execute().body();
				
				if(answer.equals("null"))
					throw new Exception();
				
				user = jsonManager.toUser(answer);
			
				url = new URL(SETBOUGHTURLBASE + "idUser=" + idUser + "&idAdvertisement=" + idAdvertisement);
				HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
				httpConnection.setRequestMethod("PUT");
				httpConnection.setDoOutput(true); 
				httpConnection.setDoInput(true);
				httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				
				reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
	
				responseBuffer = new StringBuffer();
				
				while ((inputLine = reader.readLine()) != null) {
					responseBuffer.append(inputLine);
				}
				reader.close();
	
				answer = responseBuffer.toString();
				
				System.out.println("eccomi: ");
				System.out.flush();
				
				// Invio mail di notifica
				url = new URL(NOTIFY + "?id=" + idAdvertisement + "&seller=" + emailOwner + "&buyer=" + user.getEmail());
				httpConnection = (HttpURLConnection) url.openConnection();
				httpConnection.setRequestMethod("GET");
				httpConnection.setDoOutput(true); 
				httpConnection.setDoInput(true);
				httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
	
				responseBuffer = new StringBuffer();
				
				while ((inputLine = reader.readLine()) != null) {
					responseBuffer.append(inputLine);
				}
				reader.close();
	
				answer = responseBuffer.toString();
				System.out.println("eccomi: ");
				System.out.flush();
				
				// Fine invio mail di notifica
				
			}catch(Exception e){
				e.printStackTrace();
				success="false";
			}
		}
		
		
		
		
		String urlN = returnUrl + "?success="+ success + "&idUser="+ idUser;
		String cleanUrl = urlN.replace(" ", "%20");
		
		
		try {
			response.sendRedirect(cleanUrl);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
